package org.lisy.java.math;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class BigDecimalOperate {

	public static void main(String[] args) {

		/**
		 * 科学计数法处理
		 */
		format();

		/**
		 * 运算操作
		 */
		operation();
		
		/**
		 * 比较操作
		 */
		compare();
	}

	private static void format() {
		Object value = "0E-8";
		try {
			BigDecimal bigDecimal = new BigDecimal(value + "");
			// 去掉末尾多余的0
			BigDecimal stripTrailingZeros = bigDecimal.stripTrailingZeros();
			// 避免输出科学计数法
			String result = stripTrailingZeros.toPlainString();
			System.out.println("numeric：" + result);
		} catch (Exception e) {
			System.out.println("non-numeric：" + value);
		}
	}

	private static void operation() {
		BigDecimal bignum1 = new BigDecimal("56.748525");
		BigDecimal bignum2 = new BigDecimal("10.657");

		// 加法
		BigDecimal bigDecimal = bignum1.add(bignum2);
		System.out.println("add: " + bigDecimal);

		// 减法
		bigDecimal = bignum1.subtract(bignum2);
		System.out.println("subtract: " + bigDecimal);

		// 乘法
		bigDecimal = bignum1.multiply(bignum2);
		System.out.println("multiply: " + bigDecimal);

		/**
		 * 除法
		 * 
		 * HALF_UP: 四舍五入
		 * HALF_DOWN: 四舍五入，如果结果小数位只比保留位多一位且最后一位为5则不进位
		 * UP: 始终加一
		 * DOWN: 直接截取
		 */
		bigDecimal = bignum1.divide(bignum2);
		System.out.println("divide: " + bigDecimal);
		bigDecimal = bignum1.divide(bignum2, 2, RoundingMode.HALF_UP);
		System.out.println("divide HALF_UP: " + bigDecimal);
		bigDecimal = bignum1.divide(bignum2, 2, RoundingMode.HALF_DOWN);
		System.out.println("divide HALF_DOWN: " + bigDecimal);
		bigDecimal = bignum1.divide(bignum2, 2, RoundingMode.UP);
		System.out.println("divide UP: " + bigDecimal);
		bigDecimal = bignum1.divide(bignum2, 2, RoundingMode.DOWN);
		System.out.println("divide DOWN: " + bigDecimal);
	}
	
	private static void compare() {
		BigDecimal bigDecimal = new BigDecimal("-2");
		if(bigDecimal.compareTo(BigDecimal.ZERO) == -1){
		    System.out.println(bigDecimal + " less than 0");
		}
		bigDecimal = new BigDecimal("0");
		if(bigDecimal.compareTo(BigDecimal.ZERO) == 0){
		    System.out.println(bigDecimal + " equal 0");
		}
		bigDecimal = new BigDecimal("3");
		if(bigDecimal.compareTo(BigDecimal.ZERO) == 1){
		    System.out.println(bigDecimal + " greater than 0");
		}
	}
}
